package org.example.service;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 文本转语音服务
 *
 * @author rjs
 */
@Service
public class TextToSpeechService {

    // OkHttp客户端用于发送HTTP请求
    private final OkHttpClient client = new OkHttpClient();

    /**
     * 将文本转换为语音
     *
     * @param text 要转换的文本
     * @return 语音数据字节数组
     */
    public byte[] convert(String text) throws IOException {

        // 构建文本转语音服务的HTTP请求
        HttpUrl url = new HttpUrl.Builder()
                .scheme("https")
                .host("api.oick.cn")
                .addPathSegments("txt/apiz.php")
                .addQueryParameter("text", text)
                .addQueryParameter("spd", "5")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .build();

        // 发送HTTP请求获取响应
        try (Response response = client.newCall(request).execute()) {

            // 校验响应状态
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 获取响应体字节数组
            if (response.body() != null) {
                return response.body().bytes();
            } else {
                throw new IOException("Empty response");
            }

        }

    }

}


